package com.mrobuy.jdvc.service.impl;

import com.gavel.database.SQLExecutor;
import com.gavel.utils.StringUtils;
import com.mrobuy.jdvc.entity.HtmlCache;
import com.mrobuy.jdvc.service.HtmlLodService;
import com.mrobuy.util.MD5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.mrobuy.util.HttpClientUtil;

@Service("htmlLodService")
public class HtmlLodServiceImpl implements HtmlLodService {

    private static Logger LOG = LoggerFactory.getLogger(HtmlLodService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public String load(String url) {

        if (StringUtils.isBlank(url)) {
            return "";
        }

        String id = MD5Utils.md5Hex(url);
        String suffix =  id.substring(id.length()-1);


        System.out.println(id+ ",,,,"+StringUtils.trim(suffix));
        HtmlCache htmlCache = null;
        try {
            htmlCache = jdbcTemplate.queryForObject("select * from htmlcache_" + StringUtils.trim(suffix) + "  where ID = ? ", new BeanPropertyRowMapper<>(HtmlCache.class), id);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e.getCause());
        }

        if ( htmlCache!=null && StringUtils.isNotBlank(htmlCache.getHtml()) ) {
            return  htmlCache.getHtml();
        }

//
//        string html = DriverHtmlLoader.getInstance().loadHtml(_item.getUrl(), driver -> {
//            WebDriverWait wait = new WebDriverWait(driver, 20);
//            wait.until(ExpectedConditions.textMatches(By.cssSelector("div.product-info-detail span.show-price"), PATTERN));
////                wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.crumbs")));
//            return true;
//        } );

//
//        return  htmlCache.getHtml();

        //最简单的使用：
        try {
            String html = HttpClientUtil.sendHttpGet(url);
            return html;
        }catch(Exception e){
            System.out.println(e);
            return "";
        }
    }

}
